package com.ng.stat.controller;



import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ng.common.log.annotation.SysLog;
import com.ng.common.security.SecurityUtils;
import com.ng.common.utils.*;

import com.ng.common.validator.ValidatorUtils;
import com.ng.common.validator.group.UpdateGroup;
import com.ng.stat.entity.BookEntity;
import com.ng.stat.entity.BookSortEntity;
import com.ng.stat.entity.BookWX;
import com.ng.stat.service.BookClsService;
import com.ng.stat.service.SearchService;

import com.ng.stat.service.impl.BookWxServiceImpl;
import com.ng.sys.entity.SysUserEntity;
import lombok.extern.java.Log;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Arrays;
import java.util.List;


/**
 * @author cb
 * @Description TODO
 * @date 2023/2/25
 */

@RestController
@RequestMapping("/searchbook")
//@ConditionalOnProperty(prefix="ng.upload",name = "type", havingValue = "local")
public class SearchController {

    @Autowired
    private SearchService searchService;

    @Autowired
    private BookWxServiceImpl bookWxService;

    @Autowired
    private BookClsService  bookClsService;

    @Autowired
    private SecurityUtils authUtils ;

    @Value("${ng.upload.local.PicPath:}")
    private String path ;

    @Value("${ng.upload.local.wxPath:}")
    private  String wxPath;
   // @LogAnnotation(module = "shn",operator = "获取书名")

    @RequestMapping("/getlist")
    public R<PageUtils> list(BookEntity entity , PageUtils page){
        //只有超级管理员，才能查看所有管理员列表
//		if(!getUserId().equals(Constant.SUPER_ADMIN)){
//			params.put("createUserId", getUserId());
//		}
        PageUtils pageData = searchService.queryPage(entity , page);

        return R.ok(PageUtils.class).setData( pageData);
    }

    @RequestMapping("/gethotlist")
    public R<PageUtils> hotlist(BookEntity entity , PageUtils page){
        //只有超级管理员，才能查看所有管理员列表
//		if(!getUserId().equals(Constant.SUPER_ADMIN)){
//			params.put("createUserId", getUserId());
//		}
        PageUtils pageData = searchService.gethotpage(entity , page);

        return R.ok(PageUtils.class).setData( pageData);
    }

    @RequestMapping("/getonebyid")
    public BookEntity selectone(String id){
        return  searchService.selectonebyid(id);
    }
    @RequestMapping("/findpage")
    public    R<PageUtils>  findpage(BookEntity entity , PageUtils page){

        PageUtils pageData = searchService.findListPage(entity,page);
        return R.ok(PageUtils.class).setData( pageData);

    }

    @PostMapping("/saveorupdate")

    public R<Object> update(@RequestBody BookEntity bookEntity){


        //admin用户除了自己可以修改以外,其他都不允许修改
        //另外,自己不可以直接在这里修改自己的密码
        SysUserEntity currUser = authUtils.getCurrentUser();
        String loginUserId = currUser.getUserId();
        if(bookEntity.getId()!=0){
            searchService.update(bookEntity);
        }
        else {
            searchService.insert(bookEntity);
        }


        //当前用户非admin 不可以修改admin



        //user.setCreateUserId(getUserId());
        //sysUserService.update(user);

        return R.ok();
    }

    @RequestMapping("/findpagewx")
    public    R<PageUtils>  findpagewx(BookWX entity , PageUtils page){
        PageUtils pageData = bookWxService.findListPage(entity,page);
        return R.ok(PageUtils.class).setData( pageData);

    }

    @RequestMapping("/getcount")
    public R<Object> getcount(String name){
        //只有超级管理员，才能查看所有管理员列表
//		if(!getUserId().equals(Constant.SUPER_ADMIN)){
//			params.put("createUserId", getUserId());
//		}
        Integer  bb=searchService.getcout();

        return R.ok().setData(bb);
    }

    @RequestMapping("/querygroup")
    public R<Object> querygroup(String name,String classcode){
        //只有超级管理员，才能查看所有管理员列表
//		if(!getUserId().equals(Constant.SUPER_ADMIN)){
//			params.put("createUserId", getUserId());
//		}
        Object  bb=searchService.querygroup(name,classcode);

        return R.ok().setData(bb);
    }
    @RequestMapping("/getcls")
    public  List<BookSortEntity>  querycls(BookSortEntity bookcls){
     return    bookClsService.querybookcls(bookcls);
    }

    @RequestMapping("/getclsbycode")
    public  BookSortEntity  queryclsbycode(BookSortEntity bookcls){
        return    bookClsService.querybookclsbycode(bookcls);
    }

    @RequestMapping("/getbookclsnochild")
    public List<BookSortEntity> getclsbycodenochild(BookSortEntity bookcls){
        return    bookClsService.querybookclsnochild(bookcls);
    }

    @PostMapping("/delbook")
    public R<Object> delete(@RequestBody String[] ids){
      int a=  searchService.removeByIds(ids);
        return R.ok().setData(a);
    }


    @RequestMapping("/fileexists")
    public R<Object> isFileExists(BookEntity book) throws IOException {

        String  filename=book.getFilename();
        String bkname=book.get书名();
        String  filetype=filename.substring(filename.lastIndexOf("."),filename.length());
        if(!filetype.equals(".pdf")){
            String  newfile=path+"\\"+filename.substring(0,filename.lastIndexOf("."))+".pdf";
            File file = new File(newfile);
            if(!file.exists()){
                creatbat(filename);
                if(file.exists()){
                    return R.ok();
                }
            }
            else {
                return R.ok();
            }

        }
        else {
            String absolutelyPath = path + "\\" + filename;
            File file = new File(absolutelyPath);
           if(file.exists()){

               return R.ok();
           }
           else {
               return R.error("文件不存在");
           }

        }

         return R.error("文件不存在");

    }

    @SysLog("down")
    @RequestMapping("/download")
    public  void    filestr(BookEntity book,HttpServletResponse response) throws IOException {
        String  filename=book.getFilename();

        String bkname=book.get书名();

        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.eq("id",book.getId());
        wrapper.setSql("downnum = downnum + 1");
        searchService.update(book,wrapper);

        String  filetype=filename.substring(filename.lastIndexOf("."),filename.length());
        if(!filetype.equals(".pdf")){
            String  newfile=path+"\\"+filename.substring(0,filename.lastIndexOf("."))+".pdf";
            File file = new File(newfile);
            if(!file.exists()){
                creatbat(filename);
                if(file.exists()){
                    HttpServletResponse download = FileuploadUtils.download(newfile, response,bkname+".pdf");
                }
            }
            else {
                HttpServletResponse download = FileuploadUtils.download(newfile, response,bkname+".pdf");
            }

        }
        else {
            String absolutelyPath = path + "\\" + filename;
            HttpServletResponse download = FileuploadUtils.download(absolutelyPath, response, bkname + filetype);
        }

    }


    @SysLog("preview")
    @RequestMapping("/preview")
    public  void    preview(BookEntity book,HttpServletResponse response) throws IOException {
        String  filename=book.getFilename();
        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.eq("id",book.getId());
        wrapper.setSql("previewnum = previewnum + 1");
        searchService.update(book,wrapper);
        String bkname=book.get书名();
        String  filetype=filename.substring(filename.lastIndexOf("."),filename.length());
        if(!filetype.equals(".pdf")){
            String  newfile=path+"\\"+filename.substring(0,filename.lastIndexOf("."))+".pdf";
            File file = new File(newfile);
            if(!file.exists()){
                creatbat(filename);
                if(file.exists()){
                    HttpServletResponse download = FileuploadUtils.download(newfile, response,bkname+".pdf");
                }
            }
            else {
                HttpServletResponse download = FileuploadUtils.download(newfile, response,bkname+".pdf");
            }

        }
        else {
            String absolutelyPath = path + "\\" + filename;
            HttpServletResponse download = FileuploadUtils.download(absolutelyPath, response, bkname + filetype);
        }

    }


    @RequestMapping("/downloadwx")
    public  void    filestr(BookWX book,HttpServletResponse response) throws IOException {
        String  filename=book.getDigitfilename();

        String bkname=book.getBookname();
        String  filetype=filename.substring(filename.lastIndexOf("."),filename.length());

            String absolutelyPath = wxPath + "\\" + filename;
        File file = new File(absolutelyPath);
        if(file.exists()) {
            HttpServletResponse download = FileuploadUtils.download(absolutelyPath, response, bkname + filetype);
        }
        else {
            response.setContentType("文件不存在");
        }

    }

   public void creatbat(String  filename) throws IOException{
        String  newfile=filename.substring(0,filename.lastIndexOf("."))+".pdf";
       File bat = new File("E:\\pdfdistillold\\cmd33.bat");
       String inpath="E:\\PAGES\\"+filename;
       String outpath="E:\\PAGES\\"+newfile;
       OutputStreamWriter osw =new OutputStreamWriter(
               (new FileOutputStream(bat)),"gbk");

       osw.write("E:\\pdfdistillold\\PDFDistill.exe --in "+inpath+" --out "+outpath+" --pdf");
       // osw.write("echo 执行命令\r\n");
       osw.close();
       String ret = excuteCmdCommand("E:\\pdfdistillold\\cmd33.bat");
       System.out.println(ret);
   }

    public static String excuteCmdCommand(String cmdCommand)
    {
        StringBuilder stringBuilder = new StringBuilder();
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(cmdCommand);
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), "GBK"));
            String line = null;
            while((line=bufferedReader.readLine()) != null)
            {
                stringBuilder.append(line+"\n");
            }
            return stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getDirByName(String sFileName) throws UnsupportedEncodingException {
        if (sFileName != null && !"".equals(sFileName)) {
            long lSum = 0L;
            byte[] abyResult = sFileName.toLowerCase().getBytes("GB2312");

            for(int i = 0; i < abyResult.length; ++i) {
                int x = abyResult[i] & 255;
                if (x >= 128) {
                    lSum += (long)('\uff00' + x);
                } else {
                    lSum += (long)x;
                }
            }

            lSum %= 1000L;
            return String.valueOf(lSum);
        } else {
            return "";
        }
    }

    public static String getDirByNameNew(String sFileName) throws UnsupportedEncodingException {
        String way = "1";
        if (sFileName != null && !"".equals(sFileName)) {
            long lSum = 0L;
            int i;
            if (way.equals("0")) {
                byte[] abyResult = sFileName.toLowerCase().getBytes("GBK");

                for(i = 0; i < abyResult.length; ++i) {
                    int x = abyResult[i] & 255;
                    if (x >= 128) {
                        lSum += (long)('\uff00' + x);
                    } else {
                        lSum += (long)x;
                    }
                }
            } else {
                for(i = 0; i < sFileName.length(); ++i) {
                    byte[] bytes = sFileName.substring(i, i + 1).getBytes("UTF-16LE");
                    String lCode = HexUtils.bytes2Hex(bytes[0]);
                    if (lCode.length() == 1) {
                        lCode = "0" + lCode;
                    }

                    String hCode = HexUtils.bytes2Hex(bytes[1]);
                    if (hCode.length() == 1) {
                        hCode = "0" + hCode;
                    }

                    String charCode = hCode + lCode;
                    lSum += (long)Integer.parseInt(charCode, 16);
                }
            }

            lSum %= 1000L;
            return String.valueOf(lSum);
        } else {
            return "";
        }
    }
}
